import React, { useState, useEffect } from 'react';
import styles from './index.less';
import CardCommon from '@/compontents/cardCommon';
import lhTool from 'lh-tool';
import api from '@/http/api';
import { PlusOutlined } from '@ant-design/icons';
import {
  Button,
  Form,
  Input,
  Upload,
  DatePicker,
  message,
  InputNumber,
} from 'antd';
import moment from 'moment';
import E from 'wangeditor';

let editor: any = null;
export default (props: any) => {
  const { manageId } = JSON.parse(sessionStorage.info).userInfo;
  const isAdd = props.history.location.state.isAdd;
  const initData = props.history.location.state.initData;
  const [content, setContent] = useState('');
  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 15 },
  };
  const tailLayout = {
    wrapperCol: { offset: 5, span: 15 },
  };
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );
  const [fileList1, seFileList1]: any = useState([]);
  const [fileList2, seFileList2]: any = useState([]);
  const onchange1 = (e: any) => {
    const fileLists = e.fileList;
    const len = fileLists.length;
    if (e.file.status === 'done') {
      const list: any = [...fileList1].splice(0, len - 1);
      list.push({
        uid: new Date().getTime(),
        url: e.file.response.data.src,
      });
      seFileList1(list);
    } else {
      seFileList1(fileLists);
    }
  };
  const onchange2 = (e: any) => {
    const fileLists = e.fileList;
    const len = fileLists.length;
    if (e.file.status === 'done') {
      const list: any = [...fileList2].splice(0, len - 1);
      list.push({
        uid: new Date().getTime(),
        url: e.file.response.data.src,
      });
      seFileList2(list);
    } else {
      seFileList2(fileLists);
    }
  };

  const onFinish = (v: any) => {
    if (fileList1.length && fileList2.length && editor.txt.html()) {
      if ((v.card4 && !v.card5) || (v.card5 && !v.card4)) {
        message.error('满减券原价和满减券优惠额度必须同时存在');
      } else {
        const listSrc = fileList1[0].url;
        let detailSrcs = '';
        fileList2.map((item: any) => {
          detailSrcs += `${item.url}&`;
        });
        detailSrcs = detailSrcs.slice(0, -1);
        const params = {
          title: v.title,
          listSrc,
          detailSrcs,
          intro: v.intro,
          tel: v.tel,
          address: v.address,
          endTime: lhTool.formatDate.format(
            new Date(v.endTime),
            'yyyy-MM-dd hh:mm:ss',
          ),
          businessTime: v.businessTime,
          content: editor.txt.html(),
          card1: v.card1 ? v.card1 + '' : '',
          card2: v.card2 ? v.card2 + '' : '',
          card3: v.card3 || v.card3 === 0 ? v.card3 + '' : '',
          card4: v.card4 ? `${v.card4}&${v.card5}` : '',
          manageId,
        };
        if (isAdd) {
          api.uniAdd(params).then(res => {
            props.history.push({
              pathname: '/uni',
            });
          });
        } else {
          api.uniUpdate({ ...params, id: initData.id }).then(res => {
            props.history.push({
              pathname: '/uni',
            });
          });
        }
      }
    } else {
      if (!fileList1.length) {
        message.error('请上传列表图片');
      }
      if (!fileList2.length) {
        message.error('请上传详情图片');
      }
      if (!editor.txt.html()) {
        message.error('请编写详情');
      }
    }
  };

  useEffect(() => {
    editor = new E('#edit');
    editor.config.uploadImgServer = `${process.env.apiUrl}upload/edit`;
    editor.config.onchange = (newHtml: any) => {
      setContent(newHtml);
    };
    editor.create();
    if (!isAdd) {
      seFileList1([
        {
          uid: 1,
          url: initData.listSrc,
        },
      ]);
      const arr: any = [];
      initData.detailSrcs.split('&').map((item: any, i: any) => {
        arr.push({
          uid: i + 1,
          url: item,
        });
      });
      seFileList2(arr);
      editor.txt.html(initData.content);
    }
    return () => {
      editor.destroy();
    };
  }, []);
  return (
    <CardCommon>
      <div className={styles.wrap}>
        <Form
          className={styles.form}
          {...layout}
          name="basic"
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item
            initialValue={isAdd ? '' : initData.businessTime}
            label="营业时间"
            name="businessTime"
            rules={[{ required: true, message: '请输入营业时间' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            initialValue={isAdd ? '' : moment(new Date(initData.endTime))}
            label="活动结束时间"
            name="endTime"
            rules={[{ required: true, message: '请选择活动结束时间' }]}
          >
            <DatePicker showTime format="YYYY-MM-DD HH:mm" />
          </Form.Item>
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入标题' }]}
            initialValue={isAdd ? '' : initData.title}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="简介"
            name="intro"
            rules={[{ required: true, message: '请输入简介' }]}
            initialValue={isAdd ? '' : initData.intro}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="商家电话"
            name="tel"
            rules={[{ required: true, message: '请输入商家电话' }]}
            initialValue={isAdd ? '' : initData.tel}
          >
            <Input type="number" />
          </Form.Item>
          <Form.Item
            label="商家地址"
            name="address"
            rules={[{ required: true, message: '请输入商家地址' }]}
            initialValue={isAdd ? '' : initData.address}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="列表图片"
            name="listSrc"
            rules={[{ required: false, message: '请上传列表图片' }]}
          >
            <Upload
              action={process.env.apiUrl + 'upload/image'}
              listType="picture-card"
              fileList={fileList1}
              // onPreview={this.handlePreview}
              onChange={onchange1}
            >
              {fileList1.length >= 1 ? null : uploadButton}
            </Upload>
          </Form.Item>
          <Form.Item
            label="详情图片"
            name="detailSrcs"
            rules={[{ required: false, message: '请上传详情图片' }]}
          >
            <Upload
              action={process.env.apiUrl + 'upload/image'}
              listType="picture-card"
              fileList={fileList2}
              // onPreview={this.handlePreview}
              onChange={onchange2}
            >
              {fileList2.length >= 10 ? null : uploadButton}
            </Upload>
          </Form.Item>
          <Form.Item
            label="折扣券（1-9.9折）"
            name="card1"
            rules={[{ required: false }]}
            initialValue={isAdd ? '' : initData.card1}
          >
            <InputNumber min={1} max={9.9} step={0.1} />
          </Form.Item>
          <Form.Item
            label="套餐券（0.1元以上）"
            name="card2"
            rules={[{ required: false }]}
            initialValue={isAdd ? '' : initData.card2}
          >
            <InputNumber min={0.1} step={0.1} />
          </Form.Item>
          <Form.Item
            label="体验券（0元以上包括0元）"
            name="card3"
            rules={[{ required: false }]}
            initialValue={isAdd ? '' : initData.card3}
          >
            <InputNumber min={0} step={0.1} />
          </Form.Item>
          <Form.Item
            label="满减券原价（0.1元以上）"
            name="card4"
            rules={[{ required: false }]}
            initialValue={isAdd ? '' : initData.card4.split('&')[0]}
          >
            <InputNumber min={0.1} step={0.1} />
          </Form.Item>
          <Form.Item
            label="满减券优惠额度（小于满减券原价）"
            name="card5"
            rules={[{ required: false }]}
            initialValue={isAdd ? '' : initData.card4.split('&')[1]}
          >
            <InputNumber min={0.1} step={0.1} />
          </Form.Item>
          <Form.Item
            initialValue={isAdd ? '' : initData.address}
            label="详情"
            name="content"
            rules={[{ required: false, message: '请输入详情' }]}
          >
            <div id="edit"></div>
          </Form.Item>
          <Form.Item {...tailLayout} name="btn">
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </CardCommon>
  );
};
